package com.liuche.pictureserver.process.picture;

import com.liuche.pictureserver.common.exception.ErrorCode;
import com.liuche.pictureserver.pojo.dto.PictureSaveDTO;
import com.liuche.pictureserver.process.ProcessContext;
import com.liuche.pictureserver.process.ProcessHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 图片信息，大小校验
 *
 * @author liuche
 */
@Slf4j
@Component
public class PictureCheckProcess extends ProcessHandler {

    /**
     * 处理逻辑
     *
     * @param context 上下文信息
     */
    @Override
    public void run(ProcessContext<?> context) {
        PictureSaveDTO model = (PictureSaveDTO) context.getModel();
        // 校验图片信息
        MultipartFile file = model.getFile();
        BufferedImage bufferedImage;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            log.error("upload image error：", e);
            context.setErrorCode(ErrorCode.UPLOAD_PICTURE_ERROR);
            context.setBreakFlag(true);
            return;
        }

        if (null == bufferedImage || file.isEmpty() || file.getSize() == 0) {
            log.error("上传图片异常：图片大小为空");
            context.setErrorCode(ErrorCode.UPLOAD_PICTURE_ERROR);
            context.setBreakFlag(true);
        }
    }
}
